package com.wgts.wgts.mvp.view.activity.mycenter;

import android.app.Activity;
import android.content.Intent;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.support.v4.app.FragmentManager;
import android.view.View;
import android.view.WindowManager;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.wgts.wgts.ActivityStack;
import com.wgts.wgts.R;
import com.wgts.wgts.base.BaseActivity;
import com.wgts.wgts.control.cache.CacheDataManager;
import com.wgts.wgts.control.dialog.LoadingDialogFragment;
import com.wgts.wgts.control.dialog.ToastDate;
import com.wgts.wgts.control.dialog.ToastDialogFragment;
import com.wgts.wgts.control.toast.MoHuToast;
import com.wgts.wgts.dagger.ComponentHolder;
import com.wgts.wgts.dagger.component.DaggerSystemSettingActivityComponent;
import com.wgts.wgts.dagger.module.SystemSettingActivityModule;
import com.wgts.wgts.mvp.presenter.ISystemSettingActivityPresenter;
import com.wgts.wgts.mvp.view.ISystemSettingActivityView;
import com.wgts.wgts.mvp.view.activity.main.ChangeViewPageCallBack;
import com.wgts.wgts.mvp.view.activity.main.MoHuMainActivity;
import com.wgts.wgts.netmodle.resp.AppUpdateEntity;
import com.wgts.wgts.react.MD5Util;
import com.wgts.wgts.thirdParty.push.PushTools;
import com.wgts.wgts.tools.InstallUtil;
import com.wgts.wgts.tools.UpdateDialogFragment;

import javax.inject.Inject;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

/*
 *
 *
 *   data:2018/9/2816:10
 *
 */public class SystemSettingActivity extends BaseActivity implements ISystemSettingActivityView {
    @BindView(R.id.back_btn_image)
    ImageView backBtnImage;
    @BindView(R.id.back_btn_ly)
    LinearLayout backBtnLy;
    @BindView(R.id.include_title)
    TextView includeTitle;
    @BindView(R.id.include_text)
    TextView includeText;
    @BindView(R.id.include_right_image)
    ImageView includeRightImage;
    @BindView(R.id.include_right_ly)
    LinearLayout includeRightLy;
    @BindView(R.id.message_notification)
    RelativeLayout messageNotification;
    @BindView(R.id.idea_back)
    RelativeLayout ideaBack;
    @BindView(R.id.about_platform)
    RelativeLayout aboutPlatform;
    @BindView(R.id.crash_text)
    TextView crashText;
    @BindView(R.id.clear_crash)
    RelativeLayout clearCrash;
    @BindView(R.id.version_text)
    TextView versionText;
    @BindView(R.id.updater_versions)
    RelativeLayout updaterVersions;
    @BindView(R.id.quit_login)
    LinearLayout quitLogin;

    private Handler handler = new Handler() {
        public void handleMessage(Message msg) {
            dialogDismiss();
            switch (msg.what) {
                case 0:
                    MoHuToast.showToast("清除成功");
                    try {
                        crashText.setText(CacheDataManager.getInstance(SystemSettingActivity.this).getTotalCacheSize());
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
            }
        }
    };

    private int SystemResult = 2;
    /*
    * 暂时不需要系统设置页面
    * */

    private ChangeViewPageCallBack callBack;

    @Inject
    ISystemSettingActivityPresenter presenter;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.my_center_system_setting_activity);
        ButterKnife.bind(this);
        includeTitle.setText("设置");


        PackageManager manager = this.getPackageManager();
        String name = null;
        PackageInfo info = null;
        try {
            info = manager.getPackageInfo(getPackageName(), 0);
            versionText.setText(info.versionName);
        } catch (PackageManager.NameNotFoundException e) {
            e.printStackTrace();
        }
        initView();

    }

    @Override
    public void init() {
        DaggerSystemSettingActivityComponent
                .builder()
                .appComponent(ComponentHolder.getInstance().getAppComponent())
                .systemSettingActivityModule(new SystemSettingActivityModule(this))
                .build()
                .inject(this);
    }

    private void initView(){
        try {
            crashText.setText(CacheDataManager.getInstance(SystemSettingActivity.this).getTotalCacheSize());
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @OnClick({R.id.back_btn_ly, R.id.message_notification, R.id.idea_back, R.id.about_platform, R.id.clear_crash, R.id.updater_versions, R.id.quit_login})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.back_btn_ly:
                finish();
                break;
            case R.id.message_notification:
                startNotifacation();
                //jump(MessageNotificationActivity.class);
                break;
            case R.id.idea_back:
                jump(IdeaBackActivity.class);
                break;
            case R.id.about_platform:
                jump(AboutPlatformActivity.class);
                break;
            case R.id.clear_crash:
                showDialog();
                new Thread(new clearCache()).start();
                break;
            case R.id.updater_versions:
                updateInfo();
                //updateVersion();
                break;
            case R.id.quit_login:
                //清空别名
                PushTools.getInstance().setAlias(this, "");
                presenter.quitLogin();
                break;
        }
    }

    //更新方法
    private void updateVersion(){
        ToastDate toastDate = new ToastDate();
        toastDate.setCancelQuestion("当前更新版本3.0，大小30M,建议在无线网情况下下载");
        toastDate.setCancelText("放弃更新");
        toastDate.setPointText("立即更新");
        final ToastDialogFragment toastDialogFragment = ToastDialogFragment.setToastMessage(toastDate);
        toastDialogFragment.show(getSupportFragmentManager(), "updateVersionDialog");
        toastDialogFragment.setOnClickListener(new ToastDialogFragment.OnClickListener() {
            @Override
            public void onClickCancle() {
                Toast.makeText(SystemSettingActivity.this, "选则了更新", Toast.LENGTH_SHORT).show();
                toastDialogFragment.dismiss();
            }

            @Override
            public void onClickEnsuer() {
                Toast.makeText(SystemSettingActivity.this, "放弃了更新", Toast.LENGTH_SHORT).show();
                toastDialogFragment.dismiss();
            }
        });
    }

    private void jump(Class<? extends Activity> clz){
        Intent intent = new Intent(SystemSettingActivity.this, clz);
        startActivity(intent);
    }

    private void startNotifacation() {
        Intent localIntent = new Intent();
        localIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        if (Build.VERSION.SDK_INT >= 9) {
            localIntent.setAction("android.settings.APPLICATION_DETAILS_SETTINGS");
            localIntent.setData(Uri.fromParts("package", SystemSettingActivity.this.getPackageName(), null));
        } else if (Build.VERSION.SDK_INT <= 8) {
            localIntent.setAction(Intent.ACTION_VIEW);

            localIntent.setClassName("com.android.settings",
                    "com.android.settings.InstalledAppDetails");

            localIntent.putExtra("com.android.settings.ApplicationPkgName",
                    SystemSettingActivity.this.getPackageName());
        }
        startActivity(localIntent);
    }

    @Override
    public void onError(int status, String msg) {

    }

    @Override
    public void quitLogin() {
//        Intent intent = new Intent(SystemSettingActivity.this, MoHuMainActivity.class);
//        startActivity(intent);
        for(BaseActivity activity : ActivityStack.getInstance().getActivities()){
            if(activity != null && activity instanceof MoHuMainActivity){
                ((MoHuMainActivity) activity).changeViewPage(0);
                ((MoHuMainActivity) activity).UpdateSuccess();
            }
        }
        finish();
    }

    @Override
    public void showCache(String cacheText) {

    }

    class clearCache implements Runnable {
        @Override
        public void run() {
            try {
                CacheDataManager.getInstance(SystemSettingActivity.this).clearAllCache();
                Thread.sleep(1000);
                if (CacheDataManager.getInstance(SystemSettingActivity.this).getTotalCacheSize().startsWith("0")) {
                    handler.sendEmptyMessage(0);
                }
            } catch (Exception e) {
                return;
            }
        }
    }


    @Override
    public void appUpdate(AppUpdateEntity entity) {

        String path = Environment.getExternalStorageDirectory() + "/MoHuDownFiles/" + MD5Util.encrypt(entity.url) + ".apk";

        //InstallUtil.getInstance(this, path);

        UpdateDialogFragment updateDialogFragment;

        updateDialogFragment = UpdateDialogFragment.setToastMessage(entity);

        UpdateDialogFragment.setmInstallUtil(InstallUtil.getInstance(this, path));

        if(entity.forceUpgrade == 1){

            updateDialogFragment.show(getSupportFragmentManager(), "");

        }else{
            if(entity.upgrade == 1){

                updateDialogFragment.show(getSupportFragmentManager(), "");
            }
        }
    }

    private void updateInfo(){
        PackageManager manager = this.getPackageManager();
        String name = null;
        PackageInfo info = null;
        try {
            info = manager.getPackageInfo(getPackageName(), 0);
        } catch (PackageManager.NameNotFoundException e) {
            e.printStackTrace();
        }
        name = info.versionName;
        presenter.appUpdate("", name);
    }

}
